package com.chang.reggie.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.reggie.common.R;
import com.chang.reggie.entity.Employee;
import com.chang.reggie.service.impl.EmployeeServiceImpl;
import com.chang.reggie.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServiceImpl employeeService;

    /**
     * 登录
     *
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        Employee emp = null;
        try {
            log.info("Employee {}", employee);
            // 1.将页面提交的密码进行MD5加密处理
            String password = employee.getPassword();
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            // 2.根据页面提交的用户名来查数据库
            LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Employee::getUsername, employee.getUsername());
            emp = employeeService.getOne(queryWrapper);
            // 3.如果没有查询到则返回失败结果
            if (emp == null) {
                throw new RuntimeException("登录失败");
            }
            // 4.比对密码，如果不一致则返回失败结果
            if (!password.equals(emp.getPassword())) {
                throw new RuntimeException("密码错误");
            }
            // 5.查看员工状态，如果已禁用状态，则返回员工已禁用结果
            if (Employee.INACTIVE.equals(emp.getStatus())) {
                throw new RuntimeException("账号已禁用");
            }
            // 6.登录成功，将用户id存入Session并返回成功结果
            request.getSession().setAttribute("employee", emp.getId());
        } catch (Exception e) {
            log.error(e.getMessage());
//            return R.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return R.success(emp);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        ThreadLocalUtil.remove("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("新增员工，员工信息：{}", employee);
        // 设置初始密码，需要MD5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        Long empId = ThreadLocalUtil.get("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 员工页面分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page:{}, pageSize:{}, name:{}", page, pageSize, name);
        // 创建分页构造器
        Page<Employee> employeePage = new Page<>(page, pageSize);
        // 创建条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(StrUtil.isNotBlank(name), Employee::getName, name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        // 执行查询
        employeeService.page(employeePage, queryWrapper);
        return R.success(employeePage);
    }

    /**
     * 修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        log.info(employee.toString());
//        Long empId = ThreadLocalUtil.get("employee");
//        employee.setUpdateUser(empId);
//        employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    /**
     * 获取员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable String id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到该员工信息");
    }

}
